package com.jinlejia.feedback.idea.ui;

import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.graphics.Color;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.freedom.yefeng.yfrecyclerview.YfLoadMoreListener;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.feedback.R;
import com.jinlejia.feedback.common.FbApiConfig;
import com.jinlejia.feedback.common.FbDataFilter;
import com.jinlejia.feedback.common.RecycleViewDivider;
import com.jinlejia.feedback.common.databinding.CommonEvent;
import com.jinlejia.feedback.databinding.FbActivityQuestionResponseBinding;
import com.jinlejia.feedback.idea.ui.adapter.FBTimeDropDownAdapter;
import com.jinlejia.feedback.idea.ui.adapter.FbFeedbackAdapter;
import com.jinlejia.feedback.idea.ui.bean.FbQuestionListBean;
import com.jinlejia.feedback.idea.ui.utils.FbDateUtil;
import com.jinlejia.feedback.question.ui.FbQuestionDetailsActivity;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * @author SongJiaTai
 * @description:总经理回复
 * @date :2019/6/27 23:09
 */
public class QuestionResponseActivity extends AppCompatActivity implements OnDateSetListener, SwipeRefreshLayout.OnRefreshListener, YfLoadMoreListener {
    private FbActivityQuestionResponseBinding binding;

    //日期筛选数据
    private List<View> popupViews = new ArrayList<>();
    private String time[] = {"最早日期", "最晚日期"};
    private String headers[] = {"提问日期"};
    private ListView mTimeView;
    private FBTimeDropDownAdapter timeAdapter;
    public String startTime = "";
    public String endTime = "";
    //问题类型（0：未回复  1：已回复   2：关注的问题）
    private String type = "0";
    private String keyWord = null;//搜索关键字
    private String askStartTime = null; //开始时间
    private String askEndTime = null;//结束时间
    JSONObject jsonObjectList = new JSONObject();
    JSONObject jsonObjectCount = new JSONObject();

    FbFeedbackAdapter fbFeedbackAdapter = new FbFeedbackAdapter(new ArrayList<Map<String, Object>>());

    private int pageIndex; //查询第几页
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.fb_activity_question_response);
        binding.setCommonEvent(CommonEvent.obtain());
        binding.setEvent(this);
        binding.yfListRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        binding.yfListRecyclerView.setHasFixedSize(true);
        binding.yfListRecyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, 20, Color.parseColor("#F4F4F4")));
        binding.swipeRefreshLayout.setOnRefreshListener(this);
        binding.yfListRecyclerView.enableAutoLoadMore(this);
        binding.yfListRecyclerView.setAdapter(fbFeedbackAdapter);
        fbFeedbackAdapter.changeMode(YfListMode.MODE_LOADING);

        fbFeedbackAdapter.setEventitem(new FbFeedbackAdapter.Eventitem() {
            @Override
            public void itemClick(String problemCode) {
                Intent intent = new Intent(QuestionResponseActivity.this, FbQuestionDetailsActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("problemCode",problemCode);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        initTimeDialog();
        pageIndex = 1;
        getQuestionCountAdnList(keyWord,type,20,pageIndex,askStartTime,askEndTime);

    }

    /***
     * 底部选择样式
     */
    public void OnradiobuttonChangeListener(RadioGroup group, int checkedId){
        if (checkedId == R.id.radio_notanswer) {
            type = "0";
            binding.viewNotanswer.setVisibility(View.VISIBLE);
            binding.viewAnswer.setVisibility(View.INVISIBLE);
            binding.viewIdea.setVisibility(View.INVISIBLE);
            pageIndex = 1;
            getQuestionCountAdnList(keyWord, type, 20, pageIndex, askStartTime, askEndTime);

        } else if (checkedId == R.id.radio_answer) {
            type = "1";
            pageIndex = 1;
            binding.viewNotanswer.setVisibility(View.INVISIBLE);
            binding.viewAnswer.setVisibility(View.VISIBLE);
            binding.viewIdea.setVisibility(View.INVISIBLE);
            getQuestionCountAdnList(keyWord, type, 20, pageIndex, askStartTime, askEndTime);

        } else if (checkedId == R.id.radio_ider) {
            pageIndex = 1;
            type = "2";
            binding.viewNotanswer.setVisibility(View.INVISIBLE);
            binding.viewAnswer.setVisibility(View.INVISIBLE);
            binding.viewIdea.setVisibility(View.VISIBLE);
            getQuestionCountAdnList(keyWord, type, 20, pageIndex, askStartTime, askEndTime);

        }
    }

/**
 * 初始化时间选择器
 * */
    private void initTimeDialog() {
        final View priceAreaFooter = this.getLayoutInflater().inflate(R.layout.fb_time_menu_footer, null);
        mTimeView = new ListView(this);
        timeAdapter = new FBTimeDropDownAdapter(this, Arrays.asList(time));
        mTimeView.addFooterView(priceAreaFooter);
        mTimeView.setAdapter(timeAdapter);

        //重置、确定按钮
        TextView cancel = priceAreaFooter.findViewById(R.id.bt_cancel);
        TextView confirm = priceAreaFooter.findViewById(R.id.bt_confirm);

        //点击重置
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                timeAdapter.startTime = "";
                timeAdapter.endTime = "";
                startTime = "";
                endTime = "";
                binding.dropDownMenu.setTabText("发起日期");
                timeAdapter.notifyDataSetChanged();

                askStartTime=null;
                askEndTime=null;
                jsonObjectList.remove("askEndTime");
                jsonObjectCount.remove("askEndTime");
                jsonObjectList.remove("askStartTime");
                jsonObjectCount.remove("askStartTime");
                pageIndex = 1;
                getQuestionCountAdnList(keyWord,type,20,pageIndex,askStartTime,askEndTime);
                binding.dropDownMenu.closeMenu();
            }
        });
        //确定按钮
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(startTime)){
                    CustomToast.showToast(QuestionResponseActivity.this,"请选择最早日期",1500);
                }
                if (TextUtils.isEmpty(endTime)){
                    CustomToast.showToast(QuestionResponseActivity.this,"请选择最晚日期",1500);
                }
                if (!TextUtils.isEmpty(startTime) && !TextUtils.isEmpty(endTime)) {
                    askStartTime=startTime;
                    askEndTime=endTime;
                    pageIndex = 1;
                    getQuestionCountAdnList(keyWord,type,20,pageIndex,askStartTime,askEndTime);
                    binding.dropDownMenu.closeMenu();
                }
            }
        });
        popupViews.add(mTimeView);
        TextView contentView = new TextView(this);
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0));
        contentView.setGravity(Gravity.CENTER);
        binding.dropDownMenu.setDropDownMenu(Arrays.asList(headers), popupViews, contentView);

        mTimeView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                timeAdapter.setCheckItem(position);
                show(time[position]);
            }
        });
    }

    /**
     *初始化时间弹出框
     */
    private void show(String title) {
        TimePickerDialog timePicker = new TimePickerDialog.Builder()
                .setType(Type.YEAR_MONTH_DAY)
                .setTitleStringId(title)
                .setCurrentMillseconds(System.currentTimeMillis())
                .setThemeColor(getResources().getColor(R.color.fb_yellow))
                .setWheelItemTextNormalColor(getResources().getColor(R.color.fb_hintColor))
                .setWheelItemTextSelectorColor(getResources().getColor(R.color.fb_yellow))
                .setCallBack(this)
                .build();
        timePicker.show(getSupportFragmentManager(), "year_month_day");
    }

/**
 * 实现选择器点击回调
 * */
    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        if (timePickerView.getTitle().equals("最早日期")) {
            startTime = FbDateUtil.getTimeStart(millseconds);
            timeAdapter.startTime = startTime;
        } else if (timePickerView.getTitle().equals("最晚日期")) {
            endTime = FbDateUtil.getTimeEnd(millseconds);
            timeAdapter.endTime = endTime;
        }
        timeAdapter.notifyDataSetChanged();
        if (!TextUtils.isEmpty(startTime) && !TextUtils.isEmpty(endTime)) {
            binding.dropDownMenu.setTabText(startTime + "—" + endTime);
        } else {
            binding.dropDownMenu.setTabText(startTime + endTime);
        }
    }


    /***
     * 搜索点击事件
     */
    public void search(View view){
        Intent intent = new Intent(this,FbsearchActivity.class);
        startActivityForResult(intent,101);
        jsonObjectList.remove("keyWord");
        jsonObjectCount.remove("keyWord");
    }

    /***
     * 点击全部跳转事件
     */
    public void all(View view){
        Intent intent = new Intent(this,AllQuestionActivity.class);
        startActivity(intent);
    }


    /**
     * 网络请求
     * */
    public void getQuestionCountAdnList(String keyWord, String type, int pageSize, final int pageIndex, String askStartTime, String askEndTime){
        if (!TextUtils.isEmpty(type)){
            jsonObjectList.put("type",Integer.parseInt(type));
        }
        if (!TextUtils.isEmpty(keyWord)){
            jsonObjectList.put("keyWord",keyWord);
            jsonObjectCount.put("keyWord",keyWord);
        }
        if (!TextUtils.isEmpty(askStartTime)){
            jsonObjectList.put("askStartTime",askStartTime);
            jsonObjectCount.put("askStartTime",askStartTime);
        }
        if (!TextUtils.isEmpty(askEndTime)){
            jsonObjectList.put("askEndTime",askEndTime);
            jsonObjectCount.put("askEndTime",askEndTime);
        }
        jsonObjectList.put("pageSize",pageSize);
        jsonObjectList.put("pageIndex",pageIndex);

        OkHttpUtils.postString()
                .url(FbApiConfig.GeneralManagerQuestionList)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObjectList.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        CustomToast.showToast(QuestionResponseActivity.this,"网络错误"+e.toString(),1500);
                        binding.swipeRefreshLayout.setRefreshing(false);
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        ArrayList<Map<String, Object>> data = new ArrayList<>();
                        int code = FbDataFilter.code(response);
                        if (code==700){
                            fbFeedbackAdapter.changeMode(YfListMode.MODE_ERROR);
                            return;
                        }
                        if (code == 200 && !showEmptyMessage(response)){
                            JSONArray dataList = (JSONArray) response.get("data");
                            List<FbQuestionListBean>  questionListBeans = JSON.parseArray(dataList.toString(),FbQuestionListBean.class);
                            for (FbQuestionListBean questionListBean: questionListBeans) {
                                HashMap<String,Object> map = new HashMap<>();
                                map.put("problemCode",questionListBean.getProblemCode());
                                map.put("problemTitle",questionListBean.getProblemTitle());
                                map.put("askTime",questionListBean.getAskTime());
                                map.put("isGeneral",questionListBean.getIsGeneral());
                                map.put("state",questionListBean.getState());
                                data.add(map);
                            }

                            if (pageIndex==1){
                                fbFeedbackAdapter.setData(data);
                            }else {
                                fbFeedbackAdapter.addData(data);
                            }
                        }else{
                            binding.yfListRecyclerView.enableAutoLoadMore(null);
                            if (pageIndex==1){
                                fbFeedbackAdapter.setData(data);
                            }else {
                                fbFeedbackAdapter.addData(data);
                            }
                        }
                        fbFeedbackAdapter.notifyDataSetChanged();
                        binding.swipeRefreshLayout.setRefreshing(false);
                    }
                });



        OkHttpUtils.postString()
                .url(FbApiConfig.GeneralManagerQuestionCount)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObjectCount.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        CustomToast.showToast(QuestionResponseActivity.this,"网络错误"+e.toString(),1500);
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (!showEmptyMessage(response)){
                            JSONObject data = JSON.parseObject(response.get("data").toString());
                            final Integer notReplyCount = data.getInteger("notReplyCount");//未回复个数int
                            final Integer replyCount = data.getInteger("replyCount");//已回复个数int
                            final Integer colloctCount = data.getInteger("colloctCount");//关注问题个数int

                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            binding.radioNotanswer.setText("未回复("+notReplyCount.toString()+")");
                                            binding.radioAnswer.setText("已回复("+replyCount.toString()+")");
                                            binding.radioIder.setText("关注问题("+colloctCount.toString()+")");

                                        }
                                    });
                                }
                            }).start();
                        }
                    }
                });
    }


    private boolean showEmptyMessage(Map<String, Object> response){
        if ("501".equals(String.valueOf(response.get("code")))){
            if (response.get("message") != null)
            return true;
        }
        return false;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 101) {
            pageIndex = 1;
            String name = data.getStringExtra("data");
            getQuestionCountAdnList(name,type,20,pageIndex,askStartTime,askEndTime);
        }else if(resultCode == RESULT_CANCELED && requestCode == 101){
            pageIndex = 1;
            getQuestionCountAdnList(keyWord,type,20,pageIndex,askStartTime,askEndTime);
        }
    }

    @Override
    public void onRefresh() {
        pageIndex = 1;
        binding.yfListRecyclerView.enableAutoLoadMore(this);
        binding.swipeRefreshLayout.setRefreshing(true);
        getQuestionCountAdnList(keyWord,type,20,pageIndex,askStartTime,askEndTime);
    }

    @Override
    public void loadMore() {
        pageIndex = pageIndex + 1;
        getQuestionCountAdnList(keyWord,type,20,pageIndex,askStartTime,askEndTime);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        pageIndex = 1;
        getQuestionCountAdnList(keyWord,type,20,pageIndex,askStartTime,askEndTime);
    }
}
